package com.spontaneapp.fragments;

import java.util.ArrayList;

import com.spontaneapp.R;
import com.spontaneapp.classes.Place;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class HomeFragment extends Fragment {
	
	// State
	private HomeFragmentListHandle listHandler;
	
	private ListView placeList;
	private ArrayList<Place> places;
	private PlaceAdapter adapter;
	private ArrayList<Integer> categoryImages;
	
	public HomeFragment(){}
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		placeList = (ListView)getActivity().findViewById(R.id.home_fragment_place_listview);

		places = new ArrayList<Place>();
	    initPlaces(places);
		
	    categoryImages = initCategoryImages();
		adapter = new PlaceAdapter(getActivity(), places);
		
		placeList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		placeList.setAdapter(adapter);
		
		placeList.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO - list item onClick
			}
			
		});
	}
    
    @Override
    public void onAttach(Activity activity) {
      super.onAttach(activity);
      
      /*if (activity instanceof HomeFragmentListHandle) {
        listHandler = (HomeFragmentListHandle) activity;
      } else {
        throw new ClassCastException(activity.toString()
            + " must implemenet HomeFragment.HomeFragmentListHandle");
      }*/
    }
    
    /*
     * TODO - delete after creating DB
     */
    private void initPlaces(ArrayList<Place> places) {
		places.add(new Place("Meredith's apartmentaaaaaaaa", "desc", "1.1.2013", "5 Sokolov st.aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", (float)5, 1.7, (long)1.0, (long)2.0, 0));
		places.add(new Place("Ben Gurion Univeristy", "desc2", "2.1.2013", "address2", (float)2.5, 2.7, (long)3.0, (long)6.0, 0));
	}
    
    //initialize the icons array for the categories
    // TODO - add all category icons
    // TODO - delete from home fragment and move array to singleton
  	private ArrayList<Integer> initCategoryImages() {
  		ArrayList<Integer> categoryArr = new ArrayList<Integer>();
  		categoryArr.add(R.drawable.ic_action_about);
  		return categoryArr;
  	}
    
  	/**
  	 * Holder class used in the adapter for converView uses.
  	 */
    public class Holder{
		TextView name;
		RatingBar rating;
		TextView address;
		TextView distance;
		ImageView categoryIcon;
	}
    
    private class PlaceAdapter extends BaseAdapter{
    	
    	// State
    	private LayoutInflater inflater;
		@SuppressWarnings("unused")
		private Context context;
		private ArrayList<Place> places;
		private String kmOrMile = getKMOrMile();
		
		// Constructor
		public PlaceAdapter(Context context, ArrayList<Place> places){
			//from is a factory constructor for the layout inflator - default but there's other ways
			this.inflater = LayoutInflater.from(context);
			this.context = context;
			this.places = places;
		}
		
		// Methods
		@Override
		public int getCount() {
			return places.size();
		}

		@Override
		public Object getItem(int position) {
			return places.get(position);
		}

		@Override
		//returns the id of the item in my list (if I add things in the beginning of the list that are not being showed I can skip it by adding
		//the right number to position (offset)
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder;
			if(convertView == null){
				convertView = inflater.inflate(R.layout.place_list_row_layout, parent, false);
				holder = new Holder();
				holder.name = (TextView)convertView.findViewById(R.id.place_list_item_name_textview);
				holder.rating = (RatingBar)convertView.findViewById(R.id.place_list_item_ratingBar);
				holder.address = (TextView)convertView.findViewById(R.id.place_list_item_address_textview);
				holder.distance = (TextView)convertView.findViewById(R.id.place_list_item_distance_textview);
				holder.categoryIcon = (ImageView)convertView.findViewById(R.id.place_list_item_catgory_imageview);
				convertView.setTag(holder);
			}
			else{
				holder = (Holder) convertView.getTag();
			}
			Place currPlace = places.get(position);
			boolean longName = false;
			boolean longAddr = false;
			int placeNameLen = currPlace.getName().length();
			// make sure the place name in the list will show up to 14
			if(placeNameLen > 25){
				placeNameLen = 25;
				longName = true;
			}
			if(currPlace.getName().substring(0, placeNameLen).contains("\n"))
				placeNameLen = currPlace.getName().indexOf("\n");
			int placeAddressLen = currPlace.getAddress().length();
			// make sure the place address in the list will show up to 14
			if(placeAddressLen > 30){
				placeAddressLen = 30;
				longAddr = true;
			}
			if(currPlace.getAddress().substring(0, placeAddressLen).contains("\n"))
				placeNameLen = currPlace.getAddress().indexOf("\n");
			if(longName)
				holder.name.setText(currPlace.getName().substring(0, placeNameLen) + "..");
			else
				holder.name.setText(currPlace.getName());
			holder.rating.setRating(currPlace.getRating());
			if(longAddr)
				holder.address.setText(currPlace.getAddress().substring(0, placeAddressLen) + "..");
			else
				holder.address.setText(currPlace.getAddress());
			holder.distance.setText(""+currPlace.getDistance() + kmOrMile);
			holder.categoryIcon.setImageResource(categoryImages.get(currPlace.getCategory()));
			
			return convertView;
		}
		
		/*
		 * TODO - get km or miles from shared preferences!
		 */
		private String getKMOrMile(){
			return " km";
		}
    	
    }
    
    /*
     * the interface for communication with the main activity
     */
    public interface HomeFragmentListHandle {
	    // TODO
	}
}
